/*===============================================
 *   文件名称：sg90.c
 *   创 建 者: 麦穗飘飘
 *   创建日期：2024年12月13日   15:30:58
 *   描    述：SG90 舵机驱动程序
 ================================================*/
#include "sg90.h"

/* 工作函数	*/
int work(int port, int *fd){
    *fd = socket(AF_INET, SOCK_STREAM, 0);
    if(*fd < 0){
        perror("socket");
        return 0;
    }

    int opt = 1;
    if (setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        perror("setsockopt");
        close(*fd);
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr("192.168.2.56");
    //绑定
    if(bind(*fd, (struct sockaddr *)&addr, sizeof(addr))){
        perror("bind");
    }
    //设置监听，模式
    if(listen(*fd, 3)){
        perror("listen");
    }
    //接受请求
    struct sockaddr_in cli_addr;
    socklen_t len = sizeof(cli_addr);
    int fbap = accept(*fd, (struct sockaddr *)(&cli_addr), &len);
    if(fbap < 0){
        perror("accept");
        return 0;
    }
    // printf("accept ok\n");
    printf("Qt connect A9_Board accept ok\n");
    return fbap;
}
/* 串口控制函数 */
void control_sg90(int connfd){
    char buf[32]={0};
    int serial_fd;
    while(1){
        memset(buf, 0, sizeof(buf));	//清空缓冲区
        int read_buf=recv(connfd,buf,sizeof(buf),0);	//接收数据
        if(read_buf<0)//错误
        {
            perror("recv");
            close(connfd);
            continue;
        }
        printf("recv:buf=%s\n",buf);
        serial_fd =serial_open("/dev/ttyUSB0");
        if (serial_fd < 0) {
            perror("open serial");
            continue;
        }
        serial_config(serial_fd);//配置串口

        if(read_buf> 0 && strncmp(buf, "1\n", 3) == 0)	// 1 开
        {
            printf("get serial MSG\n");
            char buf1[2];
            sprintf(buf1, "%d", 0); // 将数字0转换为字符串
            serial_write(serial_fd,buf);
            printf("serial send success\n");
        }
        close(serial_fd);
    }
}
